package mess;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LeeCode_47 {
    public static void main(String[] args) {
        int[] nums = new int[]{1, 1, 2};
        System.out.println(permuteUnique(nums));
    }

    private static List<List<Integer>> permuteUnique(int[] nums) {
        int len = nums.length;
        //1.排序
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        boolean[] used = new boolean[len];
        backTrick(result, list, nums, used);
        return result;
    }

    private static void backTrick(List<List<Integer>> result, List<Integer> list, int[] nums, boolean[] used) {
        int len = nums.length;
        if (list.size() == len) {
            result.add(new ArrayList<>(list));
            return;
        }
        for (int i = 0; i < len; i++) {
            if (used[i])
                continue;
            //剪纸条件
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1])
                continue;
            list.add(nums[i]);
            used[i] = true;

            backTrick(result, list, nums, used);
            list.remove(list.size() - 1);
            used[i] = false;
        }
    }
}
